package com.adcc.loadsheet.billing.security;

import com.adcc.loadsheet.billing.filter.ParameterCheckFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;

/**
 * springsecurity业务配置实体
 * Created by zhaoml on 2020-04-01.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//启动权限认证
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private BillingUserAuthenticationProvider billingUserAuthenticationProvider;

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private MyAuthenticationFailHander myAuthenticationFailHander;

    @Autowired
    private CustomPermissionEvaluator customPermissionEvaluator;

    //用户认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(billingUserAuthenticationProvider);
    }

    //请求处理
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/","/login","/logon").permitAll()//运行所有访问进入根目录
                // 加或不加都会将所有请求走authorizationFilter进行处理
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/login")//注销后进入登录页
//                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login")
                .loginProcessingUrl("/logon");
        http.csrf().disable();
        // 注入参数校验过滤器
//        http.addFilterBefore(authFilterRegistrationBean(), PreLogonFilter.class);
        // 注入登录拦截器
        http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        // 注入自定义权限校验器
//        http.authorizeRequests().expressionHandler(webSecurityExpressionHandler1());
        // 添加对于所有请求的head校验
        http.addFilterAt(authorizationFilter(),TokenCheckFilter.class);
        FilterConfig fc = customAuthenticationFilter().getFilterConfig();
    }

    @Bean
    public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler1(){
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(customPermissionEvaluator);
        return handler;
    }

//    @Bean
//    public Filter authFilterRegistrationBean() {
//        return new ParameterCheckFilter();
//    }

    //解决静态资源被拦截的问题
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.expressionHandler(webSecurityExpressionHandler1());
        web.ignoring().antMatchers("/webjars/**");
        web.ignoring().antMatchers("/resources/**");
        web.ignoring().antMatchers("/verifycode");
        web.ignoring().antMatchers("/**/*.js");
        web.ignoring().antMatchers("/**/*.css");
        web.ignoring().antMatchers("/**/*.png");
        web.ignoring().antMatchers("/**/*.map");
        web.ignoring().antMatchers("/**/**/*.png");
        web.ignoring().antMatchers("/**/*.jpg");
        web.ignoring().antMatchers("/**/*.gif");
        web.ignoring().antMatchers("/errorpage/errorParam");
        web.ignoring().antMatchers("/health");
        web.ignoring().antMatchers("/favicon.ico");
        web.ignoring().antMatchers("/logout");
    }

    @Bean
    PreLogonFilter customAuthenticationFilter() throws Exception {
        PreLogonFilter filter = new PreLogonFilter();
        filter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        filter.setAuthenticationFailureHandler(myAuthenticationFailHander);
        filter.setAuthenticationManager(authenticationManagerBean());
        filter.setFilterProcessesUrl("/logon");
        return filter;
    }
    @Bean
    public TokenCheckFilter authorizationFilter() throws Exception{
        return new TokenCheckFilter(authenticationManager());
    }
}